<template>
  <template v-if="$route.path === '/mockExam'">
    <el-form :inline="true" :model="queryForm" size="large" class="query">
      <el-form-item label="">
        <el-input v-model="queryForm.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">
          <Iconfont icon="icon-search" color="white">&nbsp;查询</Iconfont>
        </el-button>
      </el-form-item>
    </el-form>
    <div class="list">
      <Gridadd name="模考添加" @click="$router.push('/mockExam/add')" />
      <Griddata v-for="exam in listpage.list" :menu="generateMenu(exam)">
        <!-- 	<template #tag>
					<el-tag size="small">{{
						dictStore.getValue("PAPER_GEN_TYPE", exam.genType)
					}}</el-tag>
					&nbsp;<el-tag size="small">{{
						dictStore.getValue("MARK_STATE", exam.markState)
					}}</el-tag>
				</template> -->
        <template #title>
          {{ exam.name }}
        </template>
        <template #content>
          <div style="margin-bottom: 5px; text-align: center">
            考试时间：{{ exam.startTime }} - {{ exam.endTime }}
          </div>
          <div
            v-if="exam.markType === 2"
            style="margin-bottom: 5px; text-align: center"
          >
            阅卷时间：{{ exam.markStartTime }} -
            {{ exam.markEndTime }}
          </div>
          <el-row style="margin-bottom: 5px">
            <el-col :span="8">
              <!-- 合格分数：用字典里的吧，以后统一改 -->
              合格分数：{{ exam.passScore || "-" }}
              /
              {{ exam.totalScore }}
            </el-col>
            <el-col :span="7">
              <!-- 待批试卷：6 / 79 -->
              考试人数：{{ exam.userNum }}
            </el-col>
            <el-col :span="9">
              成绩查询：{{ dictStore.getValue("SCORE_STATE", exam.scoreState) }}
            </el-col>
            <!-- 	<el-col :span="7">
							协助批阅：{{ exam.markUserNum || "无" }}
						</el-col> -->
          </el-row>
          <el-row>
            <!-- 	<el-col :span="10">
							成绩查询：{{
								dictStore.getValue(
									"SCORE_STATE",
									exam.scoreState
								)
							}}
						</el-col> -->
            <!-- 	<el-col :span="7">
							排名：{{
								dictStore.getValue("STATE_ON", exam.rankState)
							}}
						</el-col>
						<el-col :span="7">
							防作弊：{{ exam.sxes.length > 0 ? "是" : "否" }}
						</el-col> -->
            <!-- <el-col :span="7">
                            匿名阅卷：{{ dictStore.getValue('STATE_YN', exam.anonState) }}
                        </el-col> -->
          </el-row>
        </template>
      </Griddata>
    </div>
    <el-pagination
      v-model:current-page="listpage.curPage"
      v-model:page-size="listpage.pageSize"
      :total="listpage.total"
      background
      layout="prev, pager, next"
      :hide-on-single-page="true"
      @size-change="query"
      @current-change="query"
      @prev-click="query"
      @next-click="query"
    />
  </template>
  <RouterView v-else></RouterView>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import http from "@/request";
import Griddata from "@/components/Griddata.vue";
import Gridadd from "@/components/Gridadd.vue";
import { useDictStore } from "@/stores/dict";
import type { Menu } from "@/stores/exam";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";

// 复制试卷 2024年2月24日 新增需求
import { useExamStore, type ExamQuestion, type ExamRule } from "@/stores/exam";
//  定义变量
const route = useRoute();
const router = useRouter();
const dictStore = useDictStore(); // 字典缓存
const queryForm = reactive({
  // 查询表单
  name: "",
});
const listpage = reactive({
  // 分页列表
  curPage: 1,
  pageSize: 12,
  total: 0,
  list: [] as any[],
});
const curTime = ref(); // 根据时间显示不同的按钮

// 组件挂载完成后，执行如下方法
onMounted(() => {
  query();
});

// 如果是跳转到列表页，重新查询
watch(
  () => route.path,
  (n, o) => {
    if (n === "/mockExam") {
      query();
    }
  }
);

// 获取服务器时间
const getSysTime = async () => {
  let {
    data: { data: data2 },
  } = await http.post("login/sysTime", {});
  curTime.value = dayjs(data2, "YYYY-MM-DD HH:mm:ss").toDate();
};
// 查询
async function query() {
  const {
    data: { code, data },
  } = await http.post("mockExam/listpage", {
    name: queryForm.name,
    curPage: listpage.curPage,
    pageSize: listpage.pageSize,
  });

  if (code !== 200) {
    return;
  }

  /* let {
		data: { data: data2 },
	} = await http.post("login/sysTime", {});
	curTime.value = dayjs(data2, "YYYY-MM-DD HH:mm:ss").toDate(); */
  await getSysTime();
  listpage.list = data.list;
  listpage.total = data.total;
}

// 生成菜单
function generateMenu(exam: any) {
  let menu: Menu[] = [
    {
      name: "组卷",
      icon: "icon-edit",
      event: () => router.push(`/mockExam/edit/${exam.id}`),
    },
    {
      name: "删除",
      icon: "icon-delete",
      event: () => router.push(`/mockExam/del/${exam.id}`),
    },
    {
      name: "变更时间",
      icon: "icon-time",
      event: () => router.push(`/mockExam/time/${exam.id}`),
    },
    {
      name: "统计",

      icon: "icon-statistics",
      event: () => router.push(`/mockExam/statis/${exam.id}`),
    },

    //  复制试卷 2024年2月24日 新增需求
    { name: "复制", icon: "icon-copy", event: () => copyPaper(exam.id) },
  ];

  if (exam.markState === 3) {
    // 阅卷状态（1：未阅卷；2：阅卷中；3：已阅卷；）
    return menu;
  }

  let startTime = dayjs(exam.startTime, "YYYY-MM-DD HH:mm:ss").toDate();
  let endTime = dayjs(exam.endTime, "YYYY-MM-DD HH:mm:ss").toDate();
  if (startTime.getTime() > curTime.value.getTime()) {
    menu.push({
      name: "立即开始考试",
      icon: "icon-count-down",
      event: () => setTime(exam, 1),
    });
    /* menu.push({
			name: "协助阅卷",
			icon: "icon-persons",
			event: () => router.push(`/exam/markUser/${exam.id}`),
		}); */
    return menu;
  }
  if (endTime.getTime() > curTime.value.getTime()) {
    /* menu.push({
			name: "立即完成考试",
			icon: "icon-count-down",
			event: () => setTime(exam, 2),
		}); */
    /* 	menu.push({
			name: "协助阅卷",
			icon: "icon-persons",
			event: () => router.push(`/exam/markUser/${exam.id}`),
		}); */
    return menu;
  }
  /* 
	if (exam.markType === 2) {
		// 阅卷方式（1：客观题；2：主观题；）
		let markStartTime = dayjs(
			exam.markStartTime,
			"YYYY-MM-DD HH:mm:ss"
		).toDate();
		let markEndTime = dayjs(
			exam.markEndTime,
			"YYYY-MM-DD HH:mm:ss"
		).toDate();
		if (markStartTime.getTime() > curTime.value.getTime()) {
			menu.push({
				name: "立即开始阅卷",
				icon: "icon-count-down",
				event: () => setTime(exam, 3),
			});
			menu.push({
				name: "协助阅卷",
				icon: "icon-persons",
				event: () => router.push(`/exam/markUser/${exam.id}`),
			});
			return menu;
		}
		if (markEndTime.getTime() > curTime.value.getTime()) {
			menu.push({
				name: "立即完成阅卷",
				icon: "icon-count-down",
				event: () => setTime(exam, 4),
			});
			menu.push({
				name: "协助阅卷",
				icon: "icon-persons",
				event: () => router.push(`/exam/markUser/${exam.id}`),
			});
			return menu;
		}
	} */

  return menu;
}

// 复制试卷 2024年2月24日 新增需求
// 1：查询服务器时间：
// 2：对比服务器当前时间是否和试卷开始时间相同或者之后，
// 如果是相同或者之后，那么直接复制，
// 反之，则增加

const form = useExamStore(); // 考试储存
const setDiffTime = async (nowTime, data) => {
  // if (dayjs(nowTime).isAfter(dayjs(data.startTime))) {
  // 复制时的服务器时间是在复制源的考试开始时间之后，那么就应该增加考试开始和结束时间
  // 原来的开始时间和结束时间的差异：秒
  const diffTime = dayjs(data.endTime).diff(dayjs(data.startTime), "second");
  // 设置考试开始时间
  data.startTime = dayjs(nowTime).add(1, "day").format("YYYY-MM-DD HH:mm:ss");
  // 设置结束时间
  data.endTime = dayjs(nowTime)
    .add(1, "day")
    .add(diffTime, "second")
    .format("YYYY-MM-DD HH:mm:ss");

  // 如果有阅卷
  if (data.markStartTime !== null || data.markEndTime !== null) {
    // 阅卷肯定在考试结束之后，所以直接赋值
    // 计算原来的阅卷开始时间和结束时间：秒
    const diffMarkTime = dayjs(data.markStartTime).diff(
      dayjs(data.markEndTime),
      "second"
    );
    /* 	console.log("diffMarkTime", diffMarkTime); */

    // 计算原来的阅卷开始时间和考试结束时间的差异：秒
    const diffEndTimeAndStartMarkTime = dayjs(data.markStartTime).diff(
      dayjs(data.endTime),
      "second"
    );
    /* 	console.log(
				"diffEndTimeAndStartMarkTime",
				diffEndTimeAndStartMarkTime
			); */
    // 计算阅卷开始时间
    date.markStartTime = dayjs(data.endTime)
      .add(diffEndTimeAndStartMarkTime, "second")
      .format("YYYY-MM-DD HH:mm:ss");
    // 计算阅卷结束时间
    data.markEndTime = dayjs(data.markStartTime)
      .add(diffMarkTime, "second")
      .format("YYYY-MM-DD HH:mm:ss");
  } else {
    data.markStartTime = null;
    data.markEndTime = null;
  }
  // }

  return data;
};
const setFormData = async (id) => {
  let {
    data: { code, msg, data },
  } = await http.post("mockExam/paper", { id });
  if (code !== 200) {
    ElMessage.error("获取复制源失败,请刷新尝试");
    return;
  }
  // 获取服务器时间
  // await getSysTime();
  form.id = null;
  form.name =
    data.name.length >= 25
      ? data.name.slice(0, 21) + "-复制"
      : data.name + "-复制";
  form.paperName = data.paperName;
  // 复制时，从服务器确定时间
  await getSysTime();
  const nowTime = curTime.value;

  // 如果当前复制的时间在考试开始时间相同或者之后,那么计算时间，
  // if (dayjs(nowTime).isSameOrAfter(dayjs(data.startTime))) {
  setDiffTime(nowTime, data); // 修改原因：需求是复制后可以修改，那么不管源时间，直接默认从名称开始
  // }
  form.examTimes[0] = data.startTime;
  form.examTimes[1] = data.endTime;

  if (data.markType === 2) {
    form.markTimes[0] = data.markStartTime;
    form.markTimes[1] = data.markEndTime;
  } else {
    form.markTimes[0] = null;
    form.markTimes[1] = null;
  }
  form.genType = data.genType;
  form.passScore = data.passScore;
  form.sxes = data.sxes;
  form.showType = data.showType;
  form.anonState = data.anonState;
  form.scoreState = data.scoreState;
  form.rankState = data.rankState;
  form.state = data.state;
  form.examQuestions = data.examQuestions;
  form.examRules = data.examRules;
  form.examUserIds = data.examUserIds;
  form.markUserIds = data.markUserIds;
  form.noUpdate();
};
const copyPaper = async (id) => {
  await setFormData(id);
  await publish();
};
// 复制试卷 2024年2月24日 新增需求
const publish = async () => {
  // 发布考试
  let {
    data: { code, data: processBarId },
  } = await http.post(
    "mockExam/publish",
    JSON.stringify({
      id: null,
      name: form.name,
      paperName: form.paperName,
      genType: form.genType,
      passScore: form.passScore,
      sxes: form.sxes,
      showType: form.showType,
      anonState: form.anonState,
      scoreState: form.scoreState,
      rankState: form.rankState,
      state: form.state,
      mockExamQuestionExes: form.examQuestions,
      mockExamRules: form.examRules,
      mockExamUserIds: form.examUserIds,
      markUserIds: form.markUserIds,
      totalScore: form.totalScore,
      markType: form.markType,
      startTime: form.examTimes[0],
      endTime: form.examTimes[1],
      markStartTime: form.markTimes[0],
      markEndTime: form.markTimes[1],
    }),
    { headers: { "Content-Type": "application/json" } }
  );

  if (code !== 200) {
    ElMessage.error("复制失败");
    return;
  }
  // 复制成功，重新请求获取整个列表
  ElMessage.success("复制成功,数据更新中,您也可以手动刷新");
  setTimeout(query, 1000);
};
// 设置考试时间
async function setTime(exam: any, timeType: number) {
  let {
    data: { code },
  } = await http.post("mockExam/time", {
    id: exam.id,
    timeType: timeType,
    minute: -0x7fffffff, // int最小值
  });

  if (code !== 200) {
    return;
  }
  if (timeType === 2 || timeType === 4) {
    ElMessage.success("后台正在阅卷，请稍后查询");
  } else {
    ElMessage.success("设置成功");
  }

  setTimeout(query, 2000);
}
</script>

<style lang="scss" scoped>
.list {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  .grid {
    height: 200px;
  }
}
</style>
